<template>
  <view class="detail-info">
    <view class="details">
      <view class="detail-tabs">
        <view
          v-for="(item, index) in petList"
          :key="index"
          :class="{ selected: item.current === currentIndex }"
          class="menu-item"
          @click="changeCurrent(index)"
        >
          <view>{{ item.name }}</view>
        </view>
        <!--展示在认养守护日记tabs-更新啦-->
        <view
          v-if="list.cloudAdoptInfo.readFlag === false"
          class="update-warn"
        >
          <image
            src="../../../static/detail/update-icon.png"
            style="width: 36px; height: 16px"
          ></image>
          <view class="update-text">更新啦</view>
        </view>
      </view>

      <view class="information">
        <view v-show="currentIndex === 0">
          <!--猫咪-->
          <cat-information :list="list"></cat-information>
        </view>
        <view
          v-show="currentIndex === 1 && list.status === PET_STATUS.CLOUD_ADOPT"
        >
          <!--认养守护日记-->
          <adopt-diary :list="list"></adopt-diary>
        </view>
        <view v-show="currentIndex === 2">
          <!--爱心榜-->
          <love-list :list="list"></love-list>
        </view>
      </view>
    </view>
    <view class="footer flex align-center justify-center">
      <view
        v-if="showFeeding"
        class="footer-btn"
        :class="{ 'love-btn': list.status === PET_STATUS.CLOUD_ADOPT }"
        @click="feedPet"
      >
        爱心投喂
      </view>
      <view
        v-if="
          userInfo.appUser &&
            userInfo.appUser.userId &&
            list.status === PET_STATUS.CLOUD_ADOPT &&
            userInfo.appUser.userId === list.cloudAdoptInfo.userId
        "
        class="footer-btn adopt"
        @click="feedPet"
      >
        给TA加餐
      </view>
      <view
        v-if="list.status === PET_STATUS.TOBEADOPT"
        class="footer-btn adopt"
        @click="!loadingAdopt ? cloudAdoptClick() : null"
      >
        {{ !loadingAdopt ? '云认养' : '加载中' }}
      </view>
      <view
        v-if="list.status === PET_STATUS.ADOPT"
        class="footer-btn"
        @click="viewLife"
      >
        查看它的新生活
      </view>
      <!--云认养-->
      <view
        v-if="list.status === PET_STATUS.TOBEADOPT"
        class="adopt-icon"
      >
        <image
          src="../../../static/detail/adopt@2x.png"
          style="width: 38px; height: 34px"
        ></image>
      </view>
      <!--宠物被云认养 爱心投喂展示气泡-->
      <view
        v-if="list.status === PET_STATUS.CLOUD_ADOPT"
        class="adopt-bubble"
      >
        <view class="image-border">
          <image
            src="../../../static/detail/border@2x.png"
            style="width: 180px; height: 60px"
          ></image>
        </view>
        <view class="image-icon">
          <image
            src="../../../static/detail/border-icon.png"
            style="width: 40px; height: 30px"
          ></image>
        </view>
        <view class="image-text">
          <view
            v-if="userInfo.appUser.userId === list.cloudAdoptInfo.userId"
            class="text"
          >
            主人！小猫咪的心思很简单，就想要吃个罐罐~
          </view>
          <view
            v-else
            class="text"
          >
            认养小主还没来关心我，就想要吃个罐罐~
          </view>
        </view>
      </view>
    </view>
    <u-modal
      :show="showPrompt"
      title="提示"
      :content="promptContent"
      confirm-text="我知道了"
      @confirm="confirm"
    ></u-modal>
    <cloudAdoptDialog
      v-model="cloudAdoptVisivle"
      :step="step"
      :pet-info="petInfo"
      @paySuccess="paySuccess"
    ></cloudAdoptDialog>
    <cloudAdoptCertDialog
      v-model="showCert"
      :order-sn="orderSn"
    ></cloudAdoptCertDialog>
    <maya-login-btn ref="loginBtn">
      <template #button></template>
    </maya-login-btn>
  </view>
</template>

<script>
import catInformation from './catInformation.vue';
import adoptDiary from './adoptDiary.vue';
import loveList from './loveList.vue';
import cloudAdoptDialog from '@/components/cloudAdopt/cloudAdoptDialog.vue';
import cloudAdoptCertDialog from '@/components/cloudAdopt/cloudAdoptCertDialog.vue';
import { mapGetters } from 'vuex';
import { PET_STATUS, WEB_VIEW_TYPE, TT_PAY_STATUS } from '@/const/index.js';
import { updateDiaryRead } from '@/api/detail.js';
import { checkCloudPetRenew, getTiktokPayParamOfPet } from '@/api/pet-core.js';
import { ttPay, startPay } from '@/utils/pay.js';
import { getFeedingUrl } from '@/const/webPageUrl.js';
import { navigateToWebView } from '@/utils/tools.js';
import mayaLoginBtn from '../../../components/maya-login-btn.vue';
import { isEmpty, playAdoptAudio } from '@/utils/tools';

export default {
  components: {
    catInformation,
    adoptDiary,
    loveList,
    cloudAdoptDialog,
    cloudAdoptCertDialog,
    mayaLoginBtn,
  },
  props: {
    list: {
      type: Object,
    },
  },
  data() {
    return {
      isEmpty,
      PET_STATUS,
      TT_PAY_STATUS,
      WEB_VIEW_TYPE,
      current: 0,
      navList: [],
      prevIndex: 0,
      recommedVisible: false,
      cloudAdoptVisivle: false,
      recommedInfo: {},
      showPrompt: false,
      promptContent: '',
      petInfo: {},
      step: 0,
      showCert: false,
      orderSn: '',
      currentIndex: 0,
      petList: [],
      loadingAdopt: false,
    };
  },
  watch: {
    list: {
      immediate: true, // 立即触发回调函数，即使没有变化
      handler(val) {
        if (val && val.status === PET_STATUS.CLOUD_ADOPT) {
          this.petList = [
            {
              name: '猫咪',
              current: 0,
            },
            {
              name: '认养守护日记',
              current: 1,
            },
            {
              name: '爱心榜',
              current: 2,
            },
          ];
        } else {
          this.petList = [
            {
              name: '猫咪',
              current: 0,
            },
            {
              name: '爱心榜',
              current: 2,
            },
          ];
        }
      },
    },
  },
  mounted() {
    console.log('userInfo', this.userInfo);
  },
  computed: {
    ...mapGetters(['userInfo', 'isLogin']),
    // 是否显示爱心投喂按钮
    showFeeding() {
      if (isEmpty(this.list)) {
        return true;
      }
      if (this.list.status !== PET_STATUS.ADOPT) {
        if (isEmpty(this.list.cloudAdoptInfo)) {
          return true;
        }

        return (
          this.userInfo.appUser === undefined ||
          this.userInfo.appUser.userId !== this.list.cloudAdoptInfo.userId
        );
      }
      return false;
    },
    // 是否显示给Ta加餐按钮
    // showAddmeals() {
    //   if (isEmpty(this.list)) {
    //     return false;
    //   }

    //   return (
    //     this.list.status === PET_STATUS.CLOUD_ADOPT &&
    //     this.userInfo.appUser.userId === this.list.cloudAdoptInfo.userId
    //   );
    // },
  },
  methods: {
    changeCurrent(index) {
      this.currentIndex = index;
      if (
        this.currentIndex === 1 &&
        this.list.status !== PET_STATUS.CLOUD_ADOPT
      ) {
        this.currentIndex = 2;
      }

      if (this.list.status === PET_STATUS.CLOUD_ADOPT) {
        if (this.currentIndex === 1 && isEmpty(this.userInfo)) {
          uni.showToast({
            title: '认养守护日记仅认养主人可查看',
            icon: 'none',
          });
          this.currentIndex = this.prevIndex;
          return;
        }
        //认养守护日记是否是本人打开
        if (
          this.currentIndex === 1 &&
          this.userInfo.appUser.userId === this.list.cloudAdoptInfo.userId
        ) {
          updateDiaryRead(this.list.id).then(() => {
            this.list.cloudAdoptInfo.readFlag = true;
          });
        } else if (
          this.currentIndex === 1 &&
          this.userInfo.appUser.userId !== this.list.cloudAdoptInfo.userId
        ) {
          uni.showToast({
            title: '认养守护日记仅认养主人可查看',
            icon: 'none',
          });
          this.currentIndex = this.prevIndex;
          return;
        }
      }
      this.prevIndex = index;
    },
    //查看新生活
    viewLife() {
      uni.showToast({
        title: '平台限制，请至附近有喵客户端查看',
        icon: 'none',
        duration: 1000000,
      });
    },
    change(item, event) {
      if (item.index === 1 && this.list.status !== PET_STATUS.CLOUD_ADOPT) {
        this.current = 2;
      }
      if (this.list.status === PET_STATUS.CLOUD_ADOPT) {
        //认养守护日记是否是本人打开
        if (
          item.index === 1 &&
          this.userInfo.appUser.userId === this.list.cloudAdoptInfo.userId
        ) {
          updateDiaryRead(this.list.id).then(() => {
            this.list.cloudAdoptInfo.readFlag = true;
          });
        } else if (
          item.index === 1 &&
          this.userInfo.appUser.userId !== this.list.cloudAdoptInfo.userId
        ) {
          uni.showToast({
            title: '认养守护日记仅认养主人可查看',
            icon: 'none',
          });
        }
      }
      if (
        item.index === 1 &&
        this.userInfo.appUser.userId !== this.list.cloudAdoptInfo.userId
      )
        return;
      this.current = item.index;
    },
    paySuccess(data) {
      this.orderSn = data;
      this.$emit('onRefresh');
      const that = this;
      setTimeout(() => {
        that.showCert = true;
      }, 100);
    },
    // 云认养
    async cloudAdoptClick() {
      if (!this.isLogin) {
        this.$refs.loginBtn.getMpUserInfo();
        return;
      }
      playAdoptAudio();
      this.loadingAdopt = true;
      uni.showLoading({
        title: '请求中...',
      });
      try {
        const that = this;
        that.petInfo = {
          petId: this.list.id,
          petName: this.list.nickName,
          petAvatar: this.list.avatar,
          startTime: '',
        };
        const checkRes = await checkCloudPetRenew(this.list.id);
        const code = checkRes.data.code;
        if (code === '0') {
          that.showPrompt = true;
          that.promptContent =
            '非常抱歉，有位小主刚刚下单了，但是他还没有付款呢，若他放弃云认养我，您可以稍后再来试试哦！';
        } else if (code === '3') {
          that.showPrompt = true;
          that.promptContent =
            '小猫咪已被爱心人士预约领养，马上要去新家啦！\n你可以在首页看看其他小猫咪哦';
        } else if (code === '1' && checkRes.data.sn) {
          that.orderSn = checkRes.data.sn;
          if (checkRes.data.tikTokOrderId) {
            const res = await startPay(
              checkRes.data.tikTokOrderId,
              that.orderSn
            );
            that.payResult(res);
          } else {
            const payRes = await getTiktokPayParamOfPet(checkRes.data.sn);
            const res = await ttPay(
              that.orderSn,
              payRes.data.data,
              payRes.data.token
            );
            that.payResult(res);
          }
        } else if (code === '2') {
          that.petInfo.checkType = '1';
          that.cloudAdoptVisivle = true;
          that.step = '0';
        } else {
          uni.showToast({
            title: '网络异常，请稍后再试',
            icon: 'none',
          });
        }
        that.loadingAdopt = false;
        uni.hideLoading();
      } catch (error) {
        this.loadingAdopt = false;
        throw new Error(error);
      }
    },
    ///处理支付结果
    payResult(res) {
      const that = this;
      if (res.code === TT_PAY_STATUS.SUCCESS) {
        uni.$emit('adoptSuccess');
        that.$emit('onRefresh');
        setTimeout(() => {
          that.showCert = true;
        }, 200);
      } else {
        uni.showToast({
          title: res.msg,
          icon: 'none',
        });
      }
    },

    feedPet() {
      if (!this.isLogin) {
        this.$refs.loginBtn.getMpUserInfo();
        return;
      }
      const url = getFeedingUrl(this.list.id);
      navigateToWebView({
        url,
        type: WEB_VIEW_TYPE.SHOP,
        title: '爱心投喂',
      });
    },
  },
};
</script>

<style lang="scss">
.detail-info {
  width: 100%;
  background: #fafafa;
  border-radius: 14px;
  .details {
    background: #ffffff;
    border-radius: 14px;
    height: 100%;
    padding-bottom: 80px;
    .detail-tabs {
      display: flex;
      align-items: center;
      justify-content: space-around;
      padding: 16px 0px;
      box-sizing: border-box;
      position: relative;
      .menu-item {
        font-weight: 400;
        font-size: 14px;
        color: #666666;
        position: relative;
        &.selected {
          font-weight: 500;
          font-size: 14px;
          color: #333333;
          &:after {
            content: '';
            position: absolute;
            left: 50%;
            transform: translateX(-50%);
            width: 28px;
            height: 6px;
            background: $btn-primary-color;
            border-radius: 3px;
            overflow: hidden;
          }
        }
      }

      .update-warn {
        position: absolute;
        left: 63%;
      }
      .update-text {
        font-size: 10px;
        color: #fff;
        position: absolute;
        top: 0;
        left: 3px;
      }
    }
    .information {
      padding: 0px 12px;
      box-sizing: border-box;
    }
  }
  .footer {
    position: fixed;
    background: #fff;
    bottom: 0;
    z-index: 999;
    height: 80px;
    width: 100%;
    .adopt-bubble {
      position: absolute;
      top: -40px;
      right: 18px;
      .image-border {
      }
      .image-icon {
        position: absolute;
        top: -20px;
        left: 12px;
      }
    }
    .image-text {
      position: absolute;
      top: 10px;
      .text {
        font-weight: 500;
        font-size: 12px;
        color: #e500b4;
        padding: 0px 5px;
        box-sizing: border-box;
      }
    }
    .adopt-icon {
      position: absolute;
      top: -5px;
      right: 80px;
    }
    .footer-btn {
      background: $btn-primary-color;
      border-radius: 19px;
      margin: 10px 12px;
      padding: 10px 50px;
      box-sizing: border-box;
      text-align: center;
      font-weight: 600;
      font-size: 14px;
      color: #1f1f1f;
      flex: 1;
    }
    .love-btn {
      background-image: linear-gradient(96deg, #ff7ce3 0%, #f042cb 100%);
      border-radius: 19px;
      color: #ffffff;
    }
    .adopt {
      background-image: linear-gradient(96deg, #ff7ce3 0%, #f042cb 100%);
      border-radius: 19px;
      font-weight: 600;
      font-size: 14px;
      color: #ffffff;
    }
  }
}
</style>
